<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {ref} from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import {Plus} from '@element-plus/icons-vue'
import { baseURL } from '@/utils/request'
import {artPublishService,artGetDetailService,artEditService} from '@/api/article.js'
import axios from 'axios'
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    const imageData = response.data;

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] });

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type });

    return file;
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error);
    throw error;
  }
}
const visibleDrawer=ref(false)
const judge=ref({})
const editRef=ref()
const open =async (row) => {
    visibleDrawer.value =true
    judge.value=row
    if (row.id) {
       //需要发送请求获取回写数据
       const res = await artGetDetailService(row.id)
       formModel.value = res.data.data
       imgUrl.value=baseURL+formModel.value.cover_img
       const file = await imageUrlToFile(imgUrl.value, formModel.value.cover_img)
       formModel.value.cover_img = file
       //提交给后台，需要的数据格式，是file对象格式
       //需要将网络图片地址=》转换为file对象，存储起来
    } else {
        //添加文章
      formModel.value={
         title:'',//标题
         cate_id:'',//分类
         cover_img:'',//图片
         content:'',//内容
         state:''//状态
        }
        imgUrl.value=''
        editRef.value.setHTML('')
    }
}
const formModel = ref({
    title:'',//标题
    cate_id:'',//分类
    cover_img:'',//图片
    content:'',//内容
    state:''//状态
})
defineExpose({
    open
})
//图片上传相关
const emit =defineEmits(['success'])
const imgUrl=ref('')
const onSelectFile = (uploadFile) =>{
   imgUrl.value=URL.createObjectURL(uploadFile.raw)//预览图片
   //下面一句用于文件提交
   formModel.value.cover_img = uploadFile.raw
}
const onPublish = async (state) =>{
    //将已发布还是草稿状态，存入formModel
    formModel.value.state=state
    //当前接口，需要的是formData对象
    //将普通对象 =>转换成formData对象
    const  fd = new FormData()
    for(let key in formModel.value) {
        fd.append(key,formModel.value[key])
    }
    //发请求
    if (judge.value.id) {
    //编辑操作，需要回写
       formModel.value.id=judge.value.id
       const  fd2 = new FormData()
       for(let key in formModel.value) {
        fd2.append(key,formModel.value[key])
       }
       await artEditService(fd2)
       ElMessage.success('添加成功')
       visibleDrawer.value=false
       //通知父组件，修改成功了
       emit('success','edit')
    }else{
       await artPublishService(fd)
       ElMessage.success('添加成功')
       visibleDrawer.value=false
       //通知父组件，添加成功了
       emit('success','add')
    }
}
</script>

<template>
    <el-drawer
      v-model="visibleDrawer"
      :title="judge.id ? '编辑文章' : '添加文章'"
      direction="rtl"
      size="50%"
    >
      <!-- 发表文章表单 -->
      <el-form :model="formModel" ref="formRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <channel-select
            v-model="formModel.cate_id"
            style="width: 100%;"
          ></channel-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
            <!-- 此处需要关闭elelment-plus的自动上传，不需要配置action等参数
            只需要做前端的本地预览图片即可，无需在提交前上传图标 
        语法：URL.createObjectURL(...) 创建本地预览的地址，来预览图片-->
            <el-upload
             class="avatar-uploader"
             auto-upload="false"
             :show-file-list="false"
             :on-change="onSelectFile">
                 <img v-if="imgUrl" :src="imgUrl" class="avatar">
                 <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
       </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor">
            <quill-editor 
            theme="snow"
            v-model:content="formModel.content"
            content-type="html"
            ref="editRef"></quill-editor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
          <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>